package es.mfp.practicos.view;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.primefaces.event.RowEditEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import es.mfp.practicos.domain.Factura;
import es.mfp.practicos.service.FacturasService;

@Controller("facturasBean")
@Scope("session")
public class FacturasBean {

	@Autowired
	private FacturasService facturasService;

	public void setFacturasService(FacturasService facturasService) {
		this.facturasService = facturasService;
	}

	private List<Factura> facturas = null;

	public void buscar() {
		boolean getMethod = ((HttpServletRequest) FacesContext.getCurrentInstance()
				.getExternalContext().getRequest()).getMethod().equals("GET") ? true : false;
		boolean ajaxRequest = FacesContext.getCurrentInstance().getPartialViewContext()
				.isAjaxRequest();
		boolean validationFailed = FacesContext.getCurrentInstance().isValidationFailed();

		if (getMethod && !ajaxRequest && !validationFailed) {
			facturas = facturasService.getFacturas();
		}

	}

	public List<Factura> getFacturas() {
		return facturas;
	}

	public void rowEditFacturaListener(RowEditEvent ev) {

		Factura updated = null;
		if (ev.getObject() != null && ev.getObject() instanceof Factura) {
			updated = (Factura) ev.getObject();
			facturasService.guardar(updated);

			actualizarListado(updated.getId());

			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
					"Factura actualizada correctamente", null));

		} else {
			//
		}

	}

	private void actualizarListado(Long id) {
		for (int i = 0; i < facturas.size(); i++) {
			Factura e = facturas.get(i);
			if (e.getId().equals(id)) {
				facturas.set(i, facturasService.buscarPorId(id));
				break;
			}
		}
	}

}
